// ==UserScript==
// @name         批量删除动态
// @namespace    https://yk12510.gitee.io/static-resources/
// @version      1.0.1
// @description  try to take over the world!
// @author       You
// @match        http://www.ahedu.cn/SNS/index.php?*feed_type=my*
// @grant        none
// @updateURL    https://yk12510.gitee.io/static-resources/002-script/deleteWeibo.js
// ==/UserScript==

(function () {
  'use strict'

  // Your code here...
  const deleteWeiboBtn = $('<a class="fr" href="javascript:void(0)">删除动态</a>')
  $('#right_header').prepend(deleteWeiboBtn)
  deleteWeiboBtn.click(() => {
    if (deleteWeiboBtn.text() === '停止删除') {
      clearInterval(timer)
      page = 1
      deleteWeiboBtn.text('删除动态')
    } else {
      init()
    }
  })

  // 删除动态
  function deleteWeibo (id) {
    $.post(U('public/Feed/removeFeed'), { feed_id: id }, function (msg) {
      console.log('删除')
      if (msg.status == 1) {
        if ($('#feed' + id).length > 0) {
          $('#feed' + id).fadeOut()
        }
      } else {
        ui.error(L('PUBLIC_DELETE_ERROR'))
      }
      weiboCount--
      if (weiboCount < 1) {
        init()
      }
    }, 'json')
  }

  // 加载页面
  function loadPage (page) {
    core.weibo.loadMoreByPage(`/SNS/index.php?app=widget&mod=FeedList&act=loadMore&loadId=38806912&type=following&uid=2083239&feed_type=my&feed_key=&fgid=&topic_id=&load_count=4&p=${ page }`)
  }

  // 查询Id
  function queryIds () {
    const ids = [], allIds = []
    $('#feed-lists').find('.feed_list').each((index, item) => {
      const id = $(item).attr('id').split('feed')[1],
        text = ($(item).find('a:contains(《)').text().match(/《(.+)》/) || [null, ''])[1]
      console.log(text)
      allIds.push(id);
      (/\d+$/).test(text) && ids.push(id)
    })
    return [ids, allIds]
  }

  let weiboCount = 0, page = 1, timer = null

  function init () {
    deleteWeiboBtn.text('停止删除')
    console.log('查询第' + page + '页')
    loadPage(page)
    let count = 0
    timer = setInterval(() => {
      count++
      const idsObj = queryIds(), ids = idsObj[0], allIds = idsObj[1]
      if (allIds.length || count > 2 * 60 * 1000 / 200) { // 2分钟找不到就停止
        clearInterval(timer)

        if (ids.length) {
          ids.forEach(id => {
            weiboCount++
            deleteWeibo(id)
          })
        } else { // 没有可以删除的，加载下一页
          page++
          init()
        }
      }
    }, 200)
  }
})()
